import imaplib
import email
from email.header import decode_header
import re


def get_QQemail():
    # QQ邮箱IMAP服务器地址
    IMAP_SERVER = 'imap.qq.com'
    IMAP_PORT = 993

    # 邮箱账号和授权码
    # EMAIL_ACCOUNT = '1724103494@qq.com'
    # EMAIL_PASSWORD = 'kvznxydsharbedaj'
    EMAIL_ACCOUNT = '3301068094@qq.com'
    EMAIL_PASSWORD = 'ngpeyjlfwydncieh'

    # 创建IMAP4对象并连接到服务器
    mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)

    # 登录到邮箱
    mail.login(EMAIL_ACCOUNT, EMAIL_PASSWORD)

    # 选择收件箱
    mail.select("INBOX")

    # 搜索所有未读邮件
    status, messages = mail.search(None, 'UNSEEN')
    # print(status,messages)
    # 将邮件ID存入列表
    mail_ids = messages[0].split()

    for mail_id in mail_ids:
        status, msg_data = mail.fetch(mail_id, '(RFC822)')

        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = email.message_from_bytes(response_part[1])
                subject = decode_header(msg["Subject"])[0][0]
                if isinstance(subject, bytes):
                    subject = subject.decode()
                # print("Subject:", subject)

                # 获取邮件正文
                if msg.is_multipart():
                    for part in msg.walk():
                        content_type = part.get_content_type()
                        content_disposition = str(part.get("Content-Disposition"))

                        if "attachment" not in content_disposition:
                            body = part.get_payload(decode=True).decode()
                            break
                else:
                    body = msg.get_payload(decode=True).decode()

                # 正则表达式匹配验证码（假设验证码是4位数字）
                code = re.findall(r'\b\d{4}\b', body)
                if code:
                    print(code[0])

            mail.store(mail_id, '+FLAGS', '\\Seen')
    # 登出邮箱
    mail.logout()
    return code


if __name__ == "__main__":
    get_QQemail()

